import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/travel_log_model.dart';
import '../../core/models/user_model.dart';
import '../../core/providers/travel_log_provider.dart';
import '../../core/providers/user_provider.dart';

class PreferenceShowcaseScreen extends ConsumerStatefulWidget {
  const PreferenceShowcaseScreen({super.key});

  @override
  ConsumerState<PreferenceShowcaseScreen> createState() =>
      _PreferenceShowcaseScreenState();
}

class _PreferenceShowcaseScreenState
    extends ConsumerState<PreferenceShowcaseScreen> {
  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);
    if (currentUser == null) {
      return Scaffold(
        body: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/resources/common_bg_2.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: SafeArea(
            bottom: false,
            child:
                [
                  _buildTopNavigationBar(),
                  SizedBox(height: 100.h),
                  [
                    Icon(
                      Icons.person_outline,
                      size: 80.sp,
                      color: Colors.grey[400],
                    ),
                    SizedBox(height: 20.h),
                    Text(
                      'Please login first',
                      style: TextStyle(
                        fontSize: 18.sp,
                        color: Colors.grey[600],
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      'Login to see your liked posts',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[500],
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ].toColumn(mainAxisAlignment: MainAxisAlignment.center),
                ].toColumn(),
          ),
        ),
      );
    }

    final likedLogs = ref.watch(userLikedLogsProvider(currentUser.id));
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();

    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child:
              [
                _buildTopNavigationBar(),
                SizedBox(height: 20.h),
                Expanded(
                  child:
                      likedLogs.isEmpty
                          ? _buildEmptyState()
                          : _buildContentGrid(likedLogs, allUsers),
                ),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: [
        Container(
          width: 30.w,
          height: 30.h,
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Icon(
            Icons.arrow_back_ios_new,
            color: Colors.white,
            size: 20.sp,
          ),
        ).inkWell(onTap: () => Navigator.of(context).pop()),
        Text(
          'Like',
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black,
            fontFamily: 'PoetsenOne',
          ),
        ),
        SizedBox(width: 40.w),
      ].toRow(mainAxisAlignment: MainAxisAlignment.spaceBetween),
    );
  }

  Widget _buildEmptyState() {
    return [
      SizedBox(height: 100.h),
      Icon(Icons.favorite_border, size: 80.sp, color: Colors.grey[400]),
      SizedBox(height: 20.h),
      Text(
        'No liked posts yet',
        style: TextStyle(
          fontSize: 18.sp,
          color: Colors.grey[600],
          fontWeight: FontWeight.w500,
        ),
      ),
      SizedBox(height: 8.h),
      Text(
        'Start exploring and like posts you enjoy!',
        style: TextStyle(fontSize: 14.sp, color: Colors.grey[500]),
        textAlign: TextAlign.center,
      ),
    ].toColumn(mainAxisAlignment: MainAxisAlignment.center);
  }

  Widget _buildContentGrid(
    List<TravelLogEntity> logs,
    List<UserDataEntity> allUsers,
  ) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 12.w,
          mainAxisSpacing: 12.h,
          childAspectRatio: 182 / 262,
        ),
        itemCount: logs.length,
        itemBuilder: (context, index) {
          final log = logs[index];
          final author = allUsers.firstWhere(
            (user) => user.id == log.userId,
            orElse: () => UserDataEntity.empty(),
          );
          return _buildLogItem(log, author);
        },
      ),
    );
  }

  Widget _buildLogItem(TravelLogEntity log, UserDataEntity author) {
    final currentUser = ref.watch(currentUserProvider);
    final isLiked = currentUser != null && log.isLikedByUser(currentUser.id);
    return Container(
      decoration: BoxDecoration(
        image: const DecorationImage(
          image: AssetImage('assets/resources/log_bg.png'),
          fit: BoxFit.cover,
        ),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child:
          [
            Expanded(
              child: Container(
                margin: EdgeInsets.all(8.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8.r),
                  child: Stack(
                    children: [
                      Positioned.fill(
                        child: Image.asset(
                          log.logType == TravelLogType.video
                              ? (log.videoCoverUrl ?? log.mediaUrl)
                              : log.mediaUrl,
                          fit: BoxFit.cover,
                        ),
                      ),
                      if (log.logType == TravelLogType.video)
                        Positioned.fill(
                          child: Container(
                            color: Colors.transparent,
                            child: Center(
                              child: Container(
                                width: 50.w,
                                height: 50.h,
                                decoration: BoxDecoration(
                                  color: Colors.transparent,
                                  shape: BoxShape.circle,
                                ),
                                child: Icon(
                                  AliIcons.iconPlayFill,
                                  color: Colors.white,
                                  size: 28.sp,
                                ),
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.all(8.w),
              child:
                  [
                    Text(
                      log.content,
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.black87,
                        fontWeight: FontWeight.w500,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 8.h),
                    [
                      [
                        CircleAvatar(
                          radius: 12.r,
                          backgroundImage: AssetImage(author.avatar),
                        ),
                        SizedBox(width: 6.w),
                        Flexible(
                          child: Text(
                            author.username,
                            style: TextStyle(
                              fontSize: 11.sp,
                              color: Colors.black87,
                              fontWeight: FontWeight.w600,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ].toRow(mainAxisSize: MainAxisSize.min),
                      [
                        Icon(
                          AliIcons.iconGood,
                          color: isLiked ? Colors.red : Colors.grey[600],
                          size: 20.sp,
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          '${log.likeCount}',
                          style: TextStyle(
                            fontSize: 13.sp,
                            color: Colors.black87,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ].toRow().inkWell(onTap: () => _handleLikeTap(log)),
                    ].toRow(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      mainAxisSize: MainAxisSize.max,
                    ),
                  ].toColumn(),
            ),
          ].toColumn(),
    ).inkWell(onTap: () => _handleLogTap(log));
  }

  /// 处理日志点击
  void _handleLogTap(TravelLogEntity log) {
    GoRouter.of(context).push('/journey-detail/${log.logId}');
  }

  void _handleLikeTap(TravelLogEntity log) async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) return;

    final travelLogNotifier = ref.read(travelLogProvider.notifier);
    await travelLogNotifier.toggleLike(log.logId, currentUser.id);
  }
}
